import * as types from '../../mutation-types'
import { apiGetSlider, apiGetRecommend } from '@/api'
export default () => ({
  namespaced: true,
  state: {
    swipes: [],
    list: []
  },
  mutations: {
    [types.SET_INDEX_SWIPE] (state, payload) {
      state.swipes = payload || []
    },
    [types.SET_INDEX_RECOMMEND] (state, payload) {
      state.list = payload || []
    }
  },
  actions: {
    // 首页获取轮播图方法
    [types.GET_INDEX_SWIPE] ({ commit }, payload) {
      return apiGetSlider().then(res => {
        const { data, code } = res
        if (code === 0 && data !== null) {          
          commit(`${types.SET_INDEX_SWIPE}`, data)
          return data
        } else {
          return []
        }
      })        
    },
    // 首页获取推荐列表方法
    [types.GET_INDEX_RECOMMEND] ({ commit }, payload) {
      return apiGetRecommend().then(res => {
        const { data: { list }, code } = res
        if (code === 0) {          
          commit(`${types.SET_INDEX_RECOMMEND}`, list)
          return list          
        } else {
          return []
        }
      })         
    },
    // 服务端渲染模式下提前获取数据的方法
    asyncData({ dispatch }) {
      return Promise.all([
        dispatch(types.GET_INDEX_SWIPE),
        dispatch(types.GET_INDEX_RECOMMEND)
      ])
    }
  }
})
